// xc_lshop/shop/user/transfer/index.js
var barter_order = require('../../model/barter_order')
var actbill = require('../../../../xc/model/pro_class')

Page({
  mixins: [require('../../../../xc/mixins/basicMixin')],

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    phone: "",
    remark: "",
    message: "",
    user: "",
    mode: 1, //1转账  2转账加拍照
    readonly:false,
  },
  xcloaddata: function (options, config) {
    console.log("options")
    console.log(options)
    var update = {};
    if (config.payment) {
      update["paymentconfig"] = config.payment
    }
    if (config.yihuo) {
      if (config.yihuo.status == 1) {
        update["yihuoconfig"] = config.yihuo
      } else {
        this.error("易货功能未开启", true)
      }
    }
    this.setData(update)
    this.getbasic(options.uid)
    if(options['price']){
      var price=options['price'] / 100
      price=price.toFixed(2)
      this.setData({
        readonly:true,
        amount:price
      })
      this.makeprice()
    }
  },
   //获取分类配置
   getclassinfor() {
    var that = this
    actbill.apiall().then(res => {
      console.log(res)

      if (res["status"] == 1) {
        var list=res['obj']["modellist"];
        var bclass=[];
        var sclass={};
        for(var i in list){
          var item=list[i]
          if (item['pid']==0){
            bclass.push(item);
          }else{
            if(!sclass[item['pid']]){
              sclass[item['pid']]=[]
            }
            sclass[item['pid']].push(item);
          } 
        }

         console.log(res['level'])
         console.log(bclass)
         console.log(sclass)

        that.setData({
          level: res['obj']['level'],
          bclass: bclass,
          sclass: sclass,
        })
        // that.getpagelist(that, 1)
      }
    })
  },
  onChangenav(e) {
    console.log(e)
    this.setData({
      active: e.detail.index
    })
  },
  getbasic(userid) {
    var that = this;
    barter_order.getbasic(userid).then(function (res) {
      if (res['status'] == 1) {
        var obj = res['obj']
        var update = {
          mode: 1,
          userinfo: obj['userinfo'],
        }
        if (obj['isclub'] != -1) {
          update['mode'] = 2
          that.getclassinfor()
        }else{
          update['active'] = 1
        }
        update['clubid'] = obj['isclub']

        that.setData(update)
      }
    })
  },
  onfinish(e) {
    console.log("e")
    console.log(e)
    var phone = e.detail.value;
    var message = "";
    if (phone.length < 11) {
      message = "请输入完整的手机号"
    } else {
      this.getmember(phone)
    }
    this.setData({
      phone: phone,
      message: message
    })

  },
  getmember: function (phone) {
    var that = this;
    barter_order.getmember(phone).then(function (res) {
      var user = "";
      var message = "";

      if (res["status"] == 1) {
        user = res['obj']['name'];
        if (res['obj']['nickname']) {
          user += '(' + res['obj']['nickname'] + ')'
        }
      } else {
        message = res['message']
      }
      that.setData({
        user: user,
        message: message
      })
    })
  },
  submit() {
    var that = this;
    if (that.data.doing) {
      return
    }
    if (!this.data.userinfo) {
      wx.showToast({
        icon: "none",
        title: '收款账号不能为空',
      })
      return
    }else{
      this.data.phone=this.data.userinfo.phone
    }
    if (this.data.amount <= 0) {
      wx.showToast({
        icon: "none",
        title: '金额不能为0',
      })
      return
    }
    if (this.data.amount * 1 < this.data.yihuoconfig.transferstart * 1) {
      wx.showToast({
        icon: "none",
        title: '∞'+this.data.yihuoconfig.transferstart + '起转',
      })
      return
    }

   
    if (this.data.amount  * 100 > this.data.member.memberinfo.amount * 1) {
      var name=this.data.paymentconfig.balancepayname ? this.data.paymentconfig.balancepayname : '余额'
      wx.showToast({
        icon: "none",
        title: "超出最大可转" + name
      })
      return
    }

    var data = {}
    data['phone'] = this.data.phone;
    data['amount'] = this.data.amount;
    data['remark'] = this.data.remark;
    // console.log(data);
    // return false

    var that = this;
    that.setData({
      doing: true
    })
    barter_order.transfer(data).then(function (restmodel) {

      if (restmodel["status"] == 1) {
        // var orderbill=restmodel["obj"];
        // var template_ids = restmodel["template_ids"]

        if (restmodel["paytype"] == 1) {
          var pay_params = restmodel["pay_params"];
          wx.requestPayment({
            timeStamp: pay_params["timeStamp"],
            nonceStr: pay_params["nonceStr"],
            package: pay_params["package"],
            signType: pay_params['signType'],
            paySign: pay_params["paySign"],
            success(res) {
              // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])
              that.query(restmodel)


            },
            fail(res) {
              if (res["errMsg"] == "requestPayment:fail cancel") {
                wx.showModal({
                  title: '订单未支付',
                  content: '订单未支付',
                  showCancel: false,
                  success(res) {


                    // wx.redirectTo({
                    //   url: "../order/index?opstatus=-1",
                    // })
                  }
                })
              }
              that.setData({
                doing: false
              })
            }
          })


        }else if(restmodel["paytype"] == 0){
          that.query(restmodel)
        }
      }
    })

  },
  query(restmodel) {
    var that = this;
    barter_order.queryorder(restmodel["id"]).then(function (queryreslut) {
      if (queryreslut["status"] == 1) {

        // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])

        wx.showModal({
          title: '成功',
          content: "已转账成功",
          cancelText: "返回",
          confirmText: "查看记录",
          complete: (res) => {
            if (res.cancel) {
              that.pageback('', true)
            }

            if (res.confirm) {
              wx.redirectTo({
                url: '/xc_lshop/shop/user/transfer/record',
              })
            }
          }
        })
      }
      that.setData({
        doing: false
      })
    })
  },

  afterlogin: function (options, config, userinfo) {
    console.log("userinfo")
    console.log(userinfo)
    var that = this;
    if (userinfo.member_id == 0) { //未登录
      this.login()
    }
    this.setData({
      member: userinfo
    })
    

  },
  watchinput(e) {
    var num = e.detail
    var x = String(num).indexOf(".") + 1; //得到小数点的位置
    var y = String(num).length - x; //小数点的位数
  
    if (x>0 && y >= 3) {
      num = num * 1;
      num = num.toFixed(2)
    }
    this.setData({
      amount: num
    })

    this.makeprice()

  },
  all() {
    if(!this.data.readonly){
      this.setData({
        amount: (this.data.member.memberinfo.amount / 100).toFixed(2)
      })
      this.makeprice()
    }
   
  },
  makeprice() {
    var amount = this.data.amount;
    var rate = this.data.yihuoconfig.transferval;
    

    this.setData({
      payprice: (rate * amount).toFixed(0)
    })
  },
  // 登录注册
  login() {
    var that = this;
    app.xc_sys_config.authop.oppower("login").then(function (res) {
      that.setData({
        "member": app.globalData.member
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})